package com.base.monitor.module.biz.service.cfg.impl;

import com.base.monitor.framework.util.DiskUtils;
import com.base.monitor.model.model.biz.cfg.dto.ParamSaveDto;
import com.base.monitor.module.biz.component.RefreshComponent;
import com.base.monitor.module.biz.properties.ParamProperties;
import com.base.monitor.module.biz.service.cfg.ParamService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@EnableConfigurationProperties(ParamProperties.class)
public class ParamServiceImpl implements ParamService {

    @Autowired
    private DiskUtils diskUtils;

    @Autowired
    private ParamProperties paramProperties;

    @Autowired
    private RefreshComponent refreshComponent;

    /**
     * 从配置文件中获取参数内容
     * @return
     */
    @Override
    public Map<String, String> getParam() {
        Map<String, String> map = new HashMap<>();
        map.put("allDeviceInfoUrl", paramProperties.getAllDeviceInfoUrl());
        map.put("uploadCollectDataUrl", paramProperties.getUploadCollectDataUrl());
        map.put("uploadOnlineTimeUrl", paramProperties.getUploadOnlineTimeUrl());
        return map;
    }

    /**
     * 修改参数
     * @param paramSaveDto 需要修改的参数信息
     */
    @Override
    public void editParam(ParamSaveDto paramSaveDto) {
        // 1.校验参数
        if (paramSaveDto.getAllDeviceInfoUrl() == null) {
            paramSaveDto.setAllDeviceInfoUrl("");
        }
        if (paramSaveDto.getUploadCollectDataUrl() == null) {
            paramSaveDto.setUploadCollectDataUrl("");
        }
        if (paramSaveDto.getUploadOnlineTimeUrl() == null) {
            paramSaveDto.setUploadOnlineTimeUrl("");
        }

        // 2.将更新的数据写到磁盘中
        diskUtils.updatePropertiesFile("url.allDeviceInfoUrl", paramSaveDto.getAllDeviceInfoUrl());
        diskUtils.updatePropertiesFile("url.uploadCollectDataUrl", paramSaveDto.getUploadCollectDataUrl());
        diskUtils.updatePropertiesFile("url.uploadOnlineTimeUrl", paramSaveDto.getUploadOnlineTimeUrl());

        // 3.更新paramProperties中的内容
        BeanUtils.copyProperties(paramSaveDto, paramProperties);

        // 4.重新连接MonitorQueueProducer
        refreshComponent.restart();
    }
}
